package com.cooper.scraper;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class DefineTag {

	public final static String REG_EXP = "RegExp";
	public final static String EXPRESSION_TAG = "expression";

	public static DefineTag defineTagFactory(Scraper scraper,
			XmlPullParser xml, String tagName) throws XmlPullParserException,
			IOException {
		RegExp regExp = null;
		DefineTag result = null;
		int eventType = xml.getEventType();
		boolean found = false;
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_TAG) {
				if (tagName.equals(xml.getName())) {
					found = true;
					result = new DefineTag(scraper, xml);
				} else if (found && REG_EXP.equals(xml.getName())) {
					if (regExp == null) {
						regExp = new RegExp(scraper, xml);
						result.regExp = regExp;
					} else {
						regExp = regExp.addSubRegExp(new RegExp(scraper, xml));
					}
				} else if (found && EXPRESSION_TAG.equals(xml.getName())) {
					regExp.exp = new Exp(xml);
				}
			} else if (eventType == XmlPullParser.TEXT) {
				if (found && (regExp != null) && (regExp.exp != null)
						&& (xml.getText() != null)
						&& (!"".equals(xml.getText().trim()))) {
					regExp.exp.setRule(xml.getText());
				}
			} else if (eventType == XmlPullParser.END_TAG) {
				if (found && tagName.equals(xml.getName())) {
					break;
				} else if (found && REG_EXP.equals(xml.getName())
						&& (regExp.getParentRegExp() != null)) {
					regExp = regExp.getParentRegExp();
				}
			}
			eventType = xml.next();
		}
		return result;

	}

	private Integer dest;
	private String encodeType;
	private boolean clearbuffers;
	private RegExp regExp;
	private Scraper scraper;

	public DefineTag(Scraper scraper, XmlPullParser xml) {
		this.scraper = scraper;
		String destStr = xml.getAttributeValue(null, "dest");
		dest = Integer.parseInt(destStr);
		encodeType = xml.getAttributeValue(null, "SearchStringEncoding");
		clearbuffers = Scraper.parseBool(
				xml.getAttributeValue(null, "clearbuffers"), true);
	}

	public String matchRegExp() throws XmlPullParserException, IOException {
		regExp.matchExp();
		String result = scraper.getBuffer()[dest];
		if (clearbuffers) {
			for (int i = 0; i < scraper.getBuffer().length; i++) {
				scraper.getBuffer()[i] = "";
			}
		}
		return result;
	}

	public String getEncodeType() {
		return encodeType;
	}
}
